package net.stancristian.restnews;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

	// Username and password textboxes
	EditText editTextUsername;
	EditText editTextPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		editTextUsername = (EditText) findViewById(R.id.editTextUsername);
		editTextPassword = (EditText) findViewById(R.id.editTextPassword);

		editTextPassword.setText("secret");
		editTextUsername.setText("reader1");
	}

	public void onLoginButtonClick(View v) {
		Editable username = editTextUsername.getText();
		Editable password = editTextPassword.getText();
		String baseApiAddress = getString(R.string.api_base_address);
		RestNewsClient.userName = username.toString();
		RestNewsClient.password = password.toString();
		String Url = baseApiAddress + "/User";

		HttpResponse response = RestNewsClient.getRequestWebService(Url);
		if (response != null
				&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			JSONObject obj = RestNewsClient.GetJsonObjectFromResponse(response);
			UserIdentity currentUser = new UserIdentity(obj);
			RestNewsApplication app = (RestNewsApplication) getApplicationContext();
			app.CurrentUser = currentUser;
			Toast.makeText(
					this,
					"Hello " + currentUser.FirstName + " "
							+ currentUser.LastName + "!", Toast.LENGTH_LONG)
					.show();
			GoToNextActivity(app);
		} else {
			Toast.makeText(this, "Login failed!", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void GoToNextActivity(RestNewsApplication app)
	{
		if(app.CurrentUser.Roles.contains("Admin"))
		{
			Intent goToAdmin = new Intent(this, AdminActivity.class);
			startActivity(goToAdmin);
		}
		else
		{
			Intent goToReader = new Intent(this, ReaderActivity.class);
			startActivity(goToReader);
		}
	}

}
